//
//  LXCarSellListViewController.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/8.
//

#import "LXCarSellListViewController.h"
#import "CheLiangListCell.h"
#import "CheLiangDetailViewController.h"
#import "LXSellApplyViewController.h"
#import "FuZeRenModel.h"
@interface LXCarSellListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,UITextFieldDelegate>

@property (nonatomic,strong)  UITableView       *  tableView;
@property (nonatomic, strong) NSMutableArray    *  dataAry;
@property (nonatomic, assign) NSInteger            pageIndex;
@property(nonatomic,strong)FuZeRenModel     *  selectModel;
@property(nonatomic,strong)NSString   *searchStr;
@end

@implementation LXCarSellListViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    self.searchStr = @"";
    
    self.pageIndex = 1;
    
    [self loadData];
}

- (void)viewDidLoad {
     [super viewDidLoad];
    
    self.view.backgroundColor = ColorWithF5F5F5;
    
    [self.view addSubview:self.tableView];
   
   BD_WEAKSELF
   MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       weakSelf.pageIndex = 1;
       [self loadData];
   }];

   header.lastUpdatedTimeLabel.hidden = YES;
   self.tableView.mj_header = header;
   self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
       self.pageIndex++;
       [self loadData];
   }];
   
   [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.size.mas_equalTo(CGSizeMake(ScreenWidth, kScreenHeight-StatusBarHeight-100-65));
       make.left.equalTo(self.view.mas_left).offset(0);
       make.right.equalTo(self.view.mas_right).offset(0);
       make.top.equalTo(self.view.mas_top).offset(5);
   }];
    
    
    [[kNotifyCenter rac_addObserverForName:@"carSearchText" object:nil] subscribeNext:^(NSNotification * _Nullable note) {
        self.searchStr= [NSString stringWithFormat:@"%@",note.object];
        [self loadData];
    }];
  
    
}
-(void)loadData{

    NSMutableDictionary *dic = @{
        @"page":@(self.pageIndex),
        @"rows":@(10),
        @"type":@(self.selectIndex),
    }.mutableCopy;
        
    if (!StringIsEmpty(self.searchStr)) {
        [dic setValue:self.searchStr forKey:@"carNum"];
    }
    // 全部
    if (self.selectIndex == 11) {
        [dic setValue:@(2) forKey:@"signType"];
    }
    // 已出售
    else if (self.selectIndex == 6) {
        [dic setValue:@(1) forKey:@"signType"];
    }
    
    [MSNetworkManager postRevertUrl:CarList_URL params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        [self endRefreshing];
        if (isSuccess) {
            
            if ([self.tableView.mj_header isRefreshing]||self.pageIndex==1) {
                [self.dataAry removeAllObjects];
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
            
            NSInteger totalPage = [resonseObj[@"total"] intValue];
            
            NSArray *cacheArray = resonseObj[@"list"];
            [self.dataAry addObjectsFromArray:[CheLiangModel mj_objectArrayWithKeyValuesArray:cacheArray]];
            
            if (self.dataAry.count>=totalPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
            
            [self.tableView reloadData];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self endRefreshing];
    } withShowHud:YES];
    
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataAry.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CheLiangListCell *cell = [tableView dequeueReusableCellWithIdentifier:[CheLiangListCell reuseIdentifier]];
    if (!cell) {
        cell = [[CheLiangListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[CheLiangListCell reuseIdentifier]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CheLiangModel *model = self.dataAry[indexPath.row];
    cell.sellModel = model;
    
    [cell.cancelBtn whenTapped:^{
        // 未出售
        if ([model.saleFlag intValue]==0) {
            LXSellApplyViewController *vc = [[LXSellApplyViewController alloc] init];
            vc.carModel = model;
            [self pushToNextController:vc];
        }
        
        // 出售中
        if ([model.saleFlag intValue]==1) {
            [Tool showAlertTitle:@"您确定下架吗?" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
            } commitHandlerBlock:^{
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params setObject:model.ID forKey:@"id"];
                [params setObject:@"4" forKey:@"type"];
                

                [MSNetworkManager postRevertUrl:DownUp_URL params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
                    if (isSuccess) {
                        showAlert(@"下架成功");
                        [self.tableView.mj_header beginRefreshing];
                    }
                    
                } failure:^(NSUInteger code, NSString * _Nonnull message) {
                } withShowHud:YES];
                
            } onVC:self];
            
        }
    }];
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CheLiangModel  *model = self.dataAry[indexPath.row];
    //    CheLiangDetailPageVC *VC = [[CheLiangDetailPageVC alloc] init];
    //    VC.detailModel = model;
//    model.status = @[@"未出租", @"出租中", @"已出租"][self.selectIndex - 1];
    CheLiangDetailViewController *vc = [[CheLiangDetailViewController alloc] init];
    vc.detailModel = model;
    [self pushToNextController:vc];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self loadData];
    [textField resignFirstResponder];
    return YES;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.rowHeight = 120;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.backgroundColor = ColorWithF5F5F5;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       [_tableView registerNib:[UINib nibWithNibName:[CheLiangListCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[CheLiangListCell reuseIdentifier]];
    }
    return _tableView;
}

- (NSMutableArray *)dataAry {
    if (!_dataAry) {
        self.dataAry = [NSMutableArray array];
    }
    return _dataAry;
}
#pragma mark - ------------------ DZNEmptyData ------------------
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"No_order_icon"];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (!self.tableView.mj_header.isRefreshing && !self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer resetNoMoreData];
         self.pageIndex = 1;
        [self loadData];
    }
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -50;
}
- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
@end
